<?php

class Aggregate extends Entity
{

  protected function _del($name)
  {
    try {
      return call_user_func_array(array('parent', '_del'), func_get_args());
    }
    catch (FieldNotFoundException $e) {
      try {
        return $this->getAssociation($name)->unloadData();
      }
      catch (AssociationNotFoundException $e) {
        throw new DomainException("Field or association <b>$name</b> not found in <b>{$this->getName()}</b>");
      }
    }
  }

  protected function & _get($name)
  {
    try {
      $data = call_user_func_array(array('parent', '_get'), func_get_args());
    }
    catch (FieldNotFoundException $e) {
      try {
        $this->getAssociation($name)->loadData();

        $data = & $this->data[$name];
      }
      catch (AssociationNotFoundException $e) {
        throw new DomainException("Field or association <b>$name</b> not found in <b>{$this->getName()}</b>");
      }
    }

    return $data;
  }

  protected function _has($name)
  {
    try {
      return call_user_func_array(array('parent', '_has'), func_get_args());
    }
    catch (FieldNotFoundException $e) {
      try {
        $this->getModel()->associationExists($name);

        return isset($this->data[$name]);
      }
      catch (AssociationNotFoundException $e) {
        throw new DomainException("Field or association <b>$name</b> not found in <b>{$this->getName()}</b>");
      }
    }
  }

  protected function _set($name, $value)
  {
    try {
      return call_user_func_array(array('parent', '_set'), func_get_args());
    }
    catch (FieldNotFoundException $e) {
      try {
        $this->getModel()->associationExists($name);

        $this->data[$name] = $value;
      }
      catch (AssociationNotFoundException $e) {
        throw new DomainException("Field or association <b>$name</b> not found in <b>{$this->getName()}</b>");
      }
    }
  }

  /**
   *
   * @return Association
   */
  public function getAssociation($name)
  {
    $model = $this->getModel();

    $model->associationExists($name);

    return $model->factoryAssociation($this, $name);
  }

  /**
   *
   *
   * @return AggregateModel
   */
  public function getModel()
  {
    return Domain::getObject($this);
  }

}
